package com.yuqing.myblogServe.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuqing.myblogServe.common.lang.Const;
import com.yuqing.myblogServe.common.lang.Result;
import com.yuqing.myblogServe.dao.entity.SysRole;
import com.yuqing.myblogServe.dao.entity.SysRoleMenu;
import com.yuqing.myblogServe.dao.entity.SysUserRole;
import com.yuqing.myblogServe.service.SysRoleMenuService;
import com.yuqing.myblogServe.service.SysRoleService;
import com.yuqing.myblogServe.service.SysUserRoleService;
import com.yuqing.myblogServe.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yuqing
 * @since 2022-08-02
 */
@RestController
@RequestMapping("/api/sysRole")
@Api(value = "权限管理 controller" ,tags = {"权限管理接口"})
public class SysRoleController extends BaseController {
    @Autowired
    SysRoleService sysRoleService;
    @Autowired
    SysRoleMenuService sysRoleMenuService;
    @Autowired
    SysUserRoleService sysUserRoleService;
    @Autowired
    SysUserService sysUserService;

    @GetMapping("/info/{id}")
    @PreAuthorize("hasAuthority('sys:role:list')")
    @ApiOperation(value = "id查询权限")
    public Result info(@PathVariable Long id) {
        SysRole role = sysRoleService.getById(id);
        List<SysRoleMenu> roleMenus  = sysRoleMenuService.list(new QueryWrapper<SysRoleMenu>().eq("role_id", role.getId()));
        List<Long> menuIds = roleMenus.stream().map( p -> p.getMenuId()).collect(Collectors.toList());
        role.setMenuIds(menuIds);
        return Result.succ(role);
    }

    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:role:list')")
    @ApiOperation(value = "id查询权限")
    public Result list(String name) {
        Page<SysRole> roles = sysRoleService.page(getPage(),
                new QueryWrapper<SysRole>()
                        .like(StrUtil.isNotBlank(name), "name", name)
        );
        return Result.succ(roles);
    }

    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:role:save')")
    @ApiOperation(value = "添加权限")
    public Result save(@Validated @RequestBody SysRole sysRole) {
        sysRole.setCreated(LocalDateTime.now());
        sysRole.setStatu(Const.STATUS_ON);
        sysRoleService.save(sysRole);
        return Result.succ(sysRole);
    }

    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:role:update')")
    @ApiOperation(value = "修改权限")
    public Result update(@Validated @RequestBody SysRole sysRole) {
        sysRole.setUpdated(LocalDateTime.now());
        sysRoleService.updateById(sysRole);
        return Result.succ(sysRole);
    }
    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('sys:role:delete')")
    @ApiOperation(value = "删除权限")
    public Result delete(@RequestBody Long[] ids){
        sysRoleService.removeByIds(Arrays.asList(ids));
        // 同步删除
        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().in("role_id", ids));
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().in("role_id", ids));
        return Result.succ("");
    }
    @Transactional
    @PostMapping("/perm/{roleId}")
    @PreAuthorize("hasAuthority('sys:role:perm')")
    @ApiOperation(value = "清除所有用户的权限缓存信息")
    public Result perm(@PathVariable Long roleId, @RequestBody Long[] menuIds) {
        List<SysRoleMenu> sysRoleMenus = new ArrayList<>();
        Arrays.stream(menuIds).forEach(menuId -> {
            SysRoleMenu roleMenu = new SysRoleMenu();
            roleMenu.setMenuId(menuId);
            roleMenu.setRoleId(roleId);
            sysRoleMenus.add(roleMenu);
        });

        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("role_id", roleId));

        sysRoleMenuService.saveBatch(sysRoleMenus);

        // 清除所有用户的权限缓存信息
        sysUserService.clearUserAuthorityInfoByRoleId(roleId);
        return Result.succ(menuIds);
    }

}

